// create Agora client
let swClient = null;

var localTracks = {
    videoTrack: null,
    audioTrack: null
  };
var remoteUsers = {};
// Agora client options
let options = {};
async function RTCjoin() {
  swClient = AgoraRTC.createClient({ mode: "rtc", codec: "h264" })
   // 获取数据
    let {appId, room, sig, userId} = strToJson(sessionStorage.getItem('TRTCset'));
    options = { 
      channel: room,
      uid: userId,
      token: sig,
      appid: appId
    };
    // add event listener to play remote tracks when remote user publishs.
    swClient.on("user-published", handleUserPublished);
    swClient.on("user-unpublished", handleUserUnpublished);
  
    // join a channel and create local tracks, we can use Promise.all to run them concurrently
    [ options.uid, localTracks.audioTrack, localTracks.videoTrack ] = await Promise.all([
      // join the channel
      swClient.join(options.appid, options.channel, options.token || null, options.uid),
      // create local tracks, using microphone and camera
      AgoraRTC.createMicrophoneAudioTrack(),
      AgoraRTC.createCameraVideoTrack()
    ]);
    
    // play local video track
    localTracks.videoTrack.play("videoDiv1");
  
    // publish local tracks to channel
    await swClient.publish(Object.values(localTracks));
    console.log("publish success");
}


  async function swleave() {
    console.log('退出房间')
    for (trackName in localTracks) {
      var track = localTracks[trackName];
      if(track) {
        track.stop();
        track.close();
        localTracks[trackName] = undefined;
      }
    }
  
    // remove remote users and player views
    remoteUsers = {};
    $("#videoDiv2").html("");
  
    // leave the channel
    await swClient.leave();
  
    console.log("client leaves channel success");
  }  

  async function subscribe(user, mediaType) {
    const uid = user.uid;
    // subscribe to a remote user
    await swClient.subscribe(user, mediaType);
    console.log("subscribe success");
    if (mediaType === 'video') {
      const player = $(`
        <div id="player-wrapper"  style="width: 100%; height: 100%">
          <div id="sw-player" class="player" style="width: 100%; height: 100%"></div>
        </div>
      `);
      $("#videoDiv2").append(player);
      user.videoTrack.play(`sw-player`);
    }
    if (mediaType === 'audio') {
      user.audioTrack.play();
    }
  }
  
  function handleUserPublished(user, mediaType) {
    const id = user.uid;
    remoteUsers[id] = user;
    console.log('对方进入房间-------', user, '------', mediaType )
    subscribe(user, mediaType);
  }
  
  function handleUserUnpublished(user) {
    const id = user.uid;
    delete remoteUsers[id];
    $(`#player-wrapper-${id}`).remove();
  }